package com.wang.auto.addSet;

import com.wang.conf.AppData;
import com.wang.conf.DevManager;
import com.wang.packpojo.ConMsg;
import com.wang.packpojo.ResultStatus;
import com.wang.pojo.*;
import com.wang.service.*;
import com.wang.socket.OutBoundHandler;
import com.wang.socket.SocketMap;
import com.wang.util.*;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

public class AddSetControlUtil {

    //定制附加设置 专门设备使用 不通用

    //自动化切换设备 发送指令 关闭雨水 打开污水
    public static void switchYushuiToWushui(String devGId) throws InterruptedException {


        //1、获取设备信息
        DeviceService deviceService = SpringUtil.getBean("deviceServiceImpl", DeviceServiceImpl.class);
        Device device = deviceService.selectDeviceByDevGId(devGId);
        AddAutoLinkService addAutoLinkService = SpringUtil.getBean("addAutoLinkServiceImpl", AddAutoLinkServiceImpl.class);
        AddAutoLink addAutoLink = addAutoLinkService.selectByDevGId(devGId);

        //2、开始操作
        //2.1 关闭雨水

        ResultStatus msg =  makeDevCommand(devGId,addAutoLink.getYushuiCloseControllerId());


        if(msg.getResult().equals("success")){
            //2.2 打开污水

            ResultStatus msg1 = makeDevCommand(devGId,addAutoLink.getWushuiOpenControllerId());

            if(msg1.getResult().equals("success")) {
                PrintUtil.print(device.getDevGId() + "自动模式 雨水切换污水成功");

                //修改状态
                AddSetService addSetService = SpringUtil.getBean("addSetServiceImpl",AddSetServiceImpl.class);

                Integer checkStatus = 2;
                addSetService.editCheckStatusByDevGId(devGId,checkStatus);
                //更新全局
                AddSetAutoSend.updateAddSetMsg(devGId);

                //开始切换参数
                //附加设置设备处理

                handerChangeDevCheckParam2(devGId,addAutoLink.getWushuiOpenControllerId());


                //修改控制命令污水与雨水的状态显示
                Integer yushuiNowStatus =0;
                Integer wushuiNowStatus =1;
                String funName1 = "雨水控制";
                String funName2 = "污水控制";




                DevControlFunService devControlFunService = SpringUtil.getBean("devControlFunServiceImpl",DevControlFunServiceImpl.class);

                devControlFunService.editNowStatusByFunNameAndDevId(device.getDevId(),funName1,yushuiNowStatus);
                devControlFunService.editNowStatusByFunNameAndDevId(device.getDevId(),funName2,wushuiNowStatus);





            }

        }




    }
    //自动化切换设备 发送指令 关闭污水 打开雨水
    public static void switchWushuiToYushui(String devGId) throws InterruptedException {



        //1、获取设备信息
        DeviceService deviceService = SpringUtil.getBean("deviceServiceImpl", DeviceServiceImpl.class);
        Device device = deviceService.selectDeviceByDevGId(devGId);
        AddAutoLinkService addAutoLinkService = SpringUtil.getBean("addAutoLinkServiceImpl", AddAutoLinkServiceImpl.class);
        AddAutoLink addAutoLink = addAutoLinkService.selectByDevGId(devGId);

        //2、开始操作
        //2.1 关闭污水
        ResultStatus msg =  makeDevCommand(devGId,addAutoLink.getWushuiCloseControllerId());

        if(msg.getResult().equals("success")){



            //2.2 打开雨水
            ResultStatus msg1 = makeDevCommand(devGId,addAutoLink.getYushuiOpenControllerId());

            if(msg1.getResult().equals("success")) {
                PrintUtil.print(device.getDevGId() + "自动模式 污水切换雨水成功");
                //修改状态
                AddSetService addSetService = SpringUtil.getBean("addSetServiceImpl",AddSetServiceImpl.class);

                Integer checkStatus = 1;
                addSetService.editCheckStatusByDevGId(devGId,checkStatus);
                //更新全局
                AddSetAutoSend.updateAddSetMsg(devGId);

                //开始切换参数
                //附加设置设备处理

                handerChangeDevCheckParam2(devGId,addAutoLink.getYushuiOpenControllerId());

                //修改控制命令污水与雨水的状态显示
                Integer yushuiNowStatus =1;
                Integer wushuiNowStatus =0;
                String funName1 = "雨水控制";
                String funName2 = "污水控制";

                DevControlFunService devControlFunService = SpringUtil.getBean("devControlFunServiceImpl",DevControlFunServiceImpl.class);





                devControlFunService.editNowStatusByFunNameAndDevId(device.getDevId(),funName1,yushuiNowStatus);

                devControlFunService.editNowStatusByFunNameAndDevId(device.getDevId(),funName2,wushuiNowStatus);



            }
        }




    }


    public static  ResultStatus  makeDevCommand(String devGId,Integer controlId) throws InterruptedException {

        ResultStatus msg = new ResultStatus();

        DevMControlService devMControlService = SpringUtil.getBean("devMControlServiceImpl",DevMControlServiceImpl.class);
        DevMControl devMControl = devMControlService.getById(controlId);


        ConMsg conMsg = null;
        for (Map.Entry<String, ConMsg> entry : SocketMap.mRegPassDeviceMap.entrySet()) {
            if (entry.getValue().getDevice().getDevGId().equals(devGId)) {
                conMsg = entry.getValue();
                break;
            }
        }

        if(conMsg!=null){
            //对象锁
            Object object = new Object();
            //创建全局变量对象
            Map<String, Object> resultMap1 = new HashMap<>();
            //查询该指令返回的数据回复
            DevMControlReturnService devMControlReturnService = SpringUtil.getBean("devMControlReturnServiceImpl",DevMControlReturnServiceImpl.class);
            List<DevMControlReturn> devMControlReturnList = devMControlReturnService.selectDevMControlReturnByControlId(controlId);



            resultMap1.put(controlId.toString(), null);
            if (AppData.returnMap.containsKey(devGId)) {
                AppData.returnMap.get(devGId).put(controlId.toString(), null);
            } else {
                AppData.returnMap.put(devGId, resultMap1);
            }

            ConMsg finalConMsg = conMsg;


            new Thread(() -> {
                synchronized (object) {

                    //发送给设备

                    //去除所有的空格
                    byte[] commandByte = ModBusUtil.HexString2Bytes(devMControl.getControlData());

                    OutBoundHandler.outData(finalConMsg.getCtx(), commandByte);
                    PrintUtil.print("服务端发送指令-->设备编码：" + devGId + "：" + devMControl.getControlData());
                    //计数器  //小于10秒
                    int i = 0;
                    while (i < 600) {
                        Map<String, Object> resultMap = AppData.returnMap.get(devGId);


                        try {
                            Thread.sleep(100);
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }



                        if (resultMap != null && resultMap.size() > 0 && resultMap.containsKey(devMControl.getControlId().toString()) && resultMap.get(devMControl.getControlId().toString()) != null) {
                            object.notify();
                            break;
                        }
                        i++;
                    }
                    object.notify();
                }

            }).start();
            synchronized (object) {
                object.wait(30000L);
            }

            Map<String, Object> resultMap = AppData.returnMap.get(devGId);

            if (resultMap != null && resultMap.containsKey(devMControl.getControlId().toString())) {


                String result = (String) resultMap.get(devMControl.getControlId().toString());
                if (EmptyUtil.isNotNull(result)) {
                    PrintUtil.print("指令" + devMControl.getControlData() + "http://返回结果:" + result);
                    //解析指令
                    //查询所有返回结果数据集合 比对值
                    //进行比对


                    if (devMControlReturnList.size() > 0) {

                        for (DevMControlReturn devMControlReturn : devMControlReturnList) {
                            String returnData = devMControlReturn.getControlReturnData().replaceAll(" ", "");
                            String resultData = result.replaceAll(" ", "");


                            if (returnData.equals(resultData)) {

                                AppData.returnMap.get(devGId).remove(controlId.toString());
                                msg = new ResultStatus("success", devMControlReturn.getControlReturnName());
                            }
                        }
                    } else {
                        msg = new ResultStatus("error", "设备响应超时，请稍后查看日志信息1");
                    }

                } else {
                    msg = new ResultStatus("error", "设备无响应");
                }

            } else {
                msg = new ResultStatus("error", "设备响应超时，请稍后查看日志信息2");
            }
        }else {
            msg = new ResultStatus("error", "设备离线");
        }


        return msg;
    }

    //手动模式
    public static  void handerAddSetControl(DevMControl devMControl){
        DeviceService deviceService = SpringUtil.getBean("deviceServiceImpl",DeviceServiceImpl.class);
        Device device  = deviceService.selectDeviceByDevId(devMControl.getDevId());

        String name1 = "雨水开启";
        String name2 = "污水开启";
        if(devMControl.getControlName().equals(name1)){


            handerChangeDevCheckParam2(device.getDevGId(),devMControl.getControlId());


            //修改状态
            AddSetService addSetService = SpringUtil.getBean("addSetServiceImpl",AddSetServiceImpl.class);

            Integer checkStatus = 1;
            addSetService.editCheckStatusByDevGId(device.getDevGId(),checkStatus);
            //更新全局
            AddSetAutoSend.updateAddSetMsg(device.getDevGId());

        }
        if(devMControl.getControlName().equals(name2)){

            handerChangeDevCheckParam2(device.getDevGId(),devMControl.getControlId());
            //修改状态
            AddSetService addSetService = SpringUtil.getBean("addSetServiceImpl",AddSetServiceImpl.class);

            Integer checkStatus = 2;
            addSetService.editCheckStatusByDevGId(device.getDevGId(),checkStatus);
            //更新全局
            AddSetAutoSend.updateAddSetMsg(device.getDevGId());

        }



    }




    //切换设备检测参数  //多个设备定制使用
    public static void handerChangeDevCheckParam2(String devGId,Integer controlId){




        DeviceService deviceService = SpringUtil.getBean("deviceServiceImpl",DeviceServiceImpl.class);
        Device device  = deviceService.selectDeviceByDevGId(devGId);

        DevMdtParamConfDataService devMdtParamConfDataService = SpringUtil.getBean("devMdtParamConfDataServiceImpl",DevMdtParamConfDataServiceImpl.class);

        String yuCodCode = "0229";   //雨水cod
        String yuAndanCode = "0230"; //雨水氨氮
        String yuZonglinCode = "0255"; //雨水总磷

        String wuCodCode = "0231";   //污水cod
        String wuAndanCode = "0232"; //污水氨氮
        String wuZonglinCode = "0256"; //污水总磷


        //比对指令
        //查询指令
        //从自动模式下查找   自动模式与手动模式的关联id一样
        AddAutoLinkService addAutoLinkService = SpringUtil.getBean("addAutoLinkServiceImpl",AddAutoLinkServiceImpl.class);
        AddAutoLink addAutoLink = addAutoLinkService.selectByDevGId(devGId);




        //如果是污水打开
        if(controlId.equals(addAutoLink.getWushuiOpenControllerId())){

            DevMdtParamConfData devMdtParamConfData1 = devMdtParamConfDataService.selectDevMdtParamConfDataByDevIdAndParamCode(device.getDevId(),yuCodCode);


            if(devMdtParamConfData1 !=null){
                //更改检测参数  雨水cod改 污水cod
                devMdtParamConfDataService.editCheckParamCodeById(devMdtParamConfData1.getConfDataId(),wuCodCode);
            }
            DevMdtParamConfData devMdtParamConfData2 = devMdtParamConfDataService.selectDevMdtParamConfDataByDevIdAndParamCode(device.getDevId(),yuAndanCode);
            if(devMdtParamConfData2 !=null){
                //更改检测参数  雨水氨氮 更换为污水氨氮
                devMdtParamConfDataService.editCheckParamCodeById(devMdtParamConfData2.getConfDataId(),wuAndanCode);
            }
            DevMdtParamConfData devMdtParamConfData3 = devMdtParamConfDataService.selectDevMdtParamConfDataByDevIdAndParamCode(device.getDevId(),yuZonglinCode);
            if(devMdtParamConfData3 !=null){
                //更改检测参数  雨水总磷 更换为污水总磷
                devMdtParamConfDataService.editCheckParamCodeById(devMdtParamConfData3.getConfDataId(),wuZonglinCode);
            }



            //更新全局变量参数
            PrintUtil.print("设备："+devGId+":由雨水切换成污水");
            DevManager.updateDevDate(devGId);
            //记录日志
            DevLog devLog = new DevLog();
            devLog.setDevLogTypeCode("0059");
            devLog.setDevEventTypeCode("0141");
            devLog.setDevLogContent("雨水切换污水");
            devLog.setCreateTime(DateUtil.getStrDate());
            devLog.setDevId(device.getDevId().toString());
            devLog.setIsRead(1);
            DevLogService devLogService = SpringUtil.getBean("devLogServiceImpl",DevLogServiceImpl.class);
            devLogService.addDevLog(devLog);


        }
        //如果是雨水打开
        if(controlId.equals(addAutoLink.getYushuiOpenControllerId())){
            DevMdtParamConfData devMdtParamConfData1 = devMdtParamConfDataService.selectDevMdtParamConfDataByDevIdAndParamCode(device.getDevId(),wuCodCode);
            if(devMdtParamConfData1 !=null){
                //更改检测参数  污水cod 改 雨水cod
                devMdtParamConfDataService.editCheckParamCodeById(devMdtParamConfData1.getConfDataId(),yuCodCode);
            }
            DevMdtParamConfData devMdtParamConfData2 = devMdtParamConfDataService.selectDevMdtParamConfDataByDevIdAndParamCode(device.getDevId(),wuAndanCode);
            if(devMdtParamConfData2 !=null){
                //更改检测参数 污水氨氮 改雨水氨氮
                devMdtParamConfDataService.editCheckParamCodeById(devMdtParamConfData2.getConfDataId(),yuAndanCode);
            }
            DevMdtParamConfData devMdtParamConfData3 = devMdtParamConfDataService.selectDevMdtParamConfDataByDevIdAndParamCode(device.getDevId(),wuZonglinCode);
            if(devMdtParamConfData3 !=null){
                //更改检测参数  污水总磷 改雨水总磷
                devMdtParamConfDataService.editCheckParamCodeById(devMdtParamConfData3.getConfDataId(),yuZonglinCode);
            }


            //更新全局变量参数
            PrintUtil.print("设备："+devGId+":由污水切换成雨水");
            DevManager.updateDevDate(devGId);
            //记录日志
            DevLog devLog = new DevLog();
            devLog.setDevLogTypeCode("0059");
            devLog.setDevEventTypeCode("0141");
            devLog.setDevLogContent("污水切换雨水");
            devLog.setCreateTime(DateUtil.getStrDate());
            devLog.setDevId(device.getDevId().toString());
            devLog.setIsRead(1);
            DevLogService devLogService = SpringUtil.getBean("devLogServiceImpl",DevLogServiceImpl.class);
            devLogService.addDevLog(devLog);

        }




        //更新设备发送指令时间   初始化发送时间
        for (Map.Entry<String, ConMsg> entry : SocketMap.mRegPassDeviceMap.entrySet()) {
            if (entry.getValue().getDevice().getDevGId().equals(devGId)) {
                entry.getValue().setSendCommandTime(new Date().getTime());
            }

        }





    }




}
